using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using OfficeOpenXml;
using Elderlyhealth.DAL;
using System.Data;
using iTextSharp.text;
using iTextSharp.text.pdf;


public partial class HealthReports : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Panel1.Visible = false;
            LoadHealthData();
            LoadBoundedElderlyHealthData();
            BindChartData(); // 将图表数据绑定到前端
        }
    }
    // 将健康数据绑定到前端
    private void BindChartData()
    {
        int userId = Convert.ToInt32(Session["CustomerId"]);

        using (var db = new DataClasses1DataContext())
        {
            var boundElderlyIds = db.RelativeOldMapping
                .Where(r => r.子女id == userId && r.审核状态 == true)
                .Select(r => r.老人id.ToString())
                .ToList();

            // 获取健康数据
            var healthData = db.Theath健康数据
                .Where(h => boundElderlyIds.Contains(h.old_id))
                .Select(h => new
                {
                    时间 = h.数据采集时间, // 健康数据的时间
                    心率 = h.心率,
                    收缩压 = h.收缩压,
                    舒张压 = h.舒张压
                })
                .ToList();

            // 转换为 JSON 字符串并注入到页面
            var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(healthData);
            ClientScript.RegisterStartupScript(this.GetType(), "healthChartData", $"<script>var healthChartData = {jsonData};</script>", false);
        }
    }
    private void LoadBoundedElderlyHealthData()
    {
        int userId = Convert.ToInt32(Session["CustomerId"]);
        System.Diagnostics.Debug.WriteLine("当前用户ID: " + userId);

        using (var db = new DataClasses1DataContext())
        {
            var boundElderlyIds = db.RelativeOldMapping
                         .Where(r => r.子女id == userId && r.审核状态 == true)
                         .Select(r => r.老人id.ToString())
                         .ToList();

            System.Diagnostics.Debug.WriteLine("绑定老人ID数量: " + boundElderlyIds.Count);
            foreach (var id in boundElderlyIds)
            {
                System.Diagnostics.Debug.WriteLine("绑定老人ID: " + id);
            }

            var healthData = db.Theath健康数据
                                .Where(h => boundElderlyIds.Contains(h.old_id))
                                .Select(h => new
                                {
                                    h.dataid,
                                    h.old_id,
                                    h.心率,
                                    h.收缩压,
                                    h.舒张压,
                                    h.血氧浓度,
                                    h.体温,
                                    h.数据采集时间
                                }).ToList();

            System.Diagnostics.Debug.WriteLine("健康数据数量: " + healthData.Count);
            foreach (var item in healthData)
            {
                System.Diagnostics.Debug.WriteLine($"数据: {item.dataid}, {item.old_id}, {item.心率}, {item.收缩压}");
            }

            gvHealthData.DataSource = healthData;
            gvHealthData.DataBind();
        }
    }

    private void LoadHealthData()
    {
        using (var db = new DataClasses1DataContext())
        {
            // 从健康数据表中获取数据
            var healthData = from h in db.Theath健康数据
                             select new
                             {
                                 h.dataid,
                                 h.old_id,
                                 h.心率,
                                 h.收缩压,
                                 h.舒张压,
                                 h.血氧浓度,
                                 h.体温,
                                 h.数据采集时间
                             };

            // 将数据绑定到 GridView 或其他控件
            gvHealthData.DataSource = healthData;
            gvHealthData.DataBind();
        }
    }
    protected void ExportToExcel(object sender, EventArgs e)
    {
        // 生成Excel文件
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=HealthData.xlsx");
        Response.Charset = "";
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        using (ExcelPackage pck = new ExcelPackage())
        {
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add("HealthData");
            ws.Cells["A1"].LoadFromDataTable(GetHealthDataTable(), true);
            var stream = new MemoryStream(pck.GetAsByteArray());
            stream.WriteTo(Response.OutputStream);
            Response.Flush();
            Response.End();
        }
    }
    private DataTable GetHealthDataTable()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("数据ID");
        dt.Columns.Add("老人ID");
        dt.Columns.Add("心率");
        dt.Columns.Add("收缩压");
        dt.Columns.Add("舒张压");
        dt.Columns.Add("血氧浓度");
        dt.Columns.Add("体温");
        dt.Columns.Add("数据采集时间");

        int userId = Convert.ToInt32(Session["CustomerId"]);

        using (var db = new DataClasses1DataContext())
        {
            var boundElderlyIds = db.RelativeOldMapping
                         .Where(r => r.子女id == userId && r.审核状态 == true)
                         .Select(r => r.老人id.ToString())
                         .ToList();

            var healthData = db.Theath健康数据
                               .Where(h => boundElderlyIds.Contains(h.old_id))
                               .Select(h => new
                               {
                                   h.dataid,
                                   h.old_id,
                                   h.心率,
                                   h.收缩压,
                                   h.舒张压,
                                   h.血氧浓度,
                                   h.体温,
                                   h.数据采集时间
                               }).ToList();

            foreach (var item in healthData)
            {
                DataRow row = dt.NewRow();
                row["数据ID"] = item.dataid;
                row["老人ID"] = item.old_id;
                row["心率"] = item.心率;
                row["收缩压"] = item.收缩压;
                row["舒张压"] = item.舒张压;
                row["血氧浓度"] = item.血氧浓度;
                row["体温"] = item.体温;
                row["数据采集时间"] = item.数据采集时间;
                dt.Rows.Add(row);
            }
        }

        return dt;
    }
    /*  // 假设已经有一个 ExportToExcel 方法，可以重新命名
      protected void ExportToExcelFile(object sender, EventArgs e)
      {
          // 原始导出代码
          Response.Clear();
          Response.Buffer = true;
          Response.AddHeader("content-disposition", "attachment;filename=HealthData.xlsx");
          Response.Charset = "";
          Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

          using (ExcelPackage pck = new ExcelPackage())
          {
              ExcelWorksheet ws = pck.Workbook.Worksheets.Add("HealthData");
              ws.Cells["A1"].LoadFromDataTable(GetHealthDataTable(), true);
              var stream = new MemoryStream(pck.GetAsByteArray());
              stream.WriteTo(Response.OutputStream);
              Response.Flush();
              Response.End();
          }
      }*/

    protected void btnFilter_Click(object sender, EventArgs e)
    {
        DateTime startDate = DateTime.Parse(txtStartDate.Text);
        DateTime endDate = DateTime.Parse(txtEndDate.Text);

        using (var db = new DataClasses1DataContext())
        {
            int userId = Convert.ToInt32(Session["CustomerId"]);
            var boundElderlyIds = db.RelativeOldMapping
                                 .Where(r => r.子女id == userId && r.审核状态 == true)
                                 .Select(r => r.老人id.ToString())
                                 .ToList();

            var filteredHealthData = db.Theath健康数据
                             .Where(h => boundElderlyIds.Contains(h.old_id) &&
                                         h.数据采集时间 >= startDate &&
                                         h.数据采集时间 <= endDate)
                             .Select(h => new
                             {
                                 dataid = h.dataid,          // 字段保持中文名
                                 old_id = h.old_id,
                                 心率 = h.心率,
                                 收缩压 = h.收缩压,
                                 舒张压 = h.舒张压,
                                 血氧浓度 = h.血氧浓度,
                                 体温 = h.体温,
                                 数据采集时间 = h.数据采集时间
                             }).ToList();

            if (filteredHealthData.Count == 0)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "NoData", "<script>alert('筛选范围内没有数据！');</script>");
                return;
            }

            gvHealthData.DataSource = filteredHealthData;
            gvHealthData.DataBind();

            // 将筛选后的数据传递到前端
            var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(filteredHealthData, new Newtonsoft.Json.JsonSerializerSettings
            {
                DateFormatString = "yyyy-MM-ddTHH:mm:ss"
            });
            ClientScript.RegisterStartupScript(this.GetType(), "updateChart", $"<script>updateHealthChart({jsonData});</script>", false);
        }
    }








    protected void btnShowAll_Click(object sender, EventArgs e)
    {
        txtStartDate.Text = string.Empty;
        txtEndDate.Text = string.Empty;

        using (var db = new DataClasses1DataContext())
        {
            int userId = Convert.ToInt32(Session["CustomerId"]);
            var boundElderlyIds = db.RelativeOldMapping
                         .Where(r => r.子女id == userId && r.审核状态 == true)
                         .Select(r => r.老人id.ToString())
                         .ToList();

            var allHealthData = db.Theath健康数据
                     .Where(h => boundElderlyIds.Contains(h.old_id))
                     .Select(h => new
                     {
                         dataid = h.dataid,          // 字段保持中文名
                         old_id = h.old_id,
                         心率 = h.心率,
                         收缩压 = h.收缩压,
                         舒张压 = h.舒张压,
                         血氧浓度 = h.血氧浓度,
                         体温 = h.体温,
                         数据采集时间 = h.数据采集时间
                     }).ToList();

            gvHealthData.DataSource = allHealthData;
            gvHealthData.DataBind();

            var jsonData = Newtonsoft.Json.JsonConvert.SerializeObject(allHealthData, new Newtonsoft.Json.JsonSerializerSettings
            {
                DateFormatString = "yyyy-MM-dd HH:mm:ss"
            });
            ClientScript.RegisterStartupScript(this.GetType(), "updateChart", $"<script>updateHealthChart({jsonData});</script>", false);
        }
    }


    protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        DateTime? startDate = string.IsNullOrEmpty(txtStartDate.Text) ? (DateTime?)null : DateTime.Parse(txtStartDate.Text);
        DateTime? endDate = string.IsNullOrEmpty(txtEndDate.Text) ? (DateTime?)null : DateTime.Parse(txtEndDate.Text);

        var healthData = GetFilteredHealthData(startDate, endDate);

        if (healthData == null || healthData.Count == 0)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "NoData", "<script>alert('没有可导出的数据！');</script>");
            return;
        }

        // 转换为 DataTable
        DataTable dt = new DataTable();
        dt.Columns.Add("数据ID");
        dt.Columns.Add("老人ID");
        dt.Columns.Add("心率");
        dt.Columns.Add("收缩压");
        dt.Columns.Add("舒张压");
        dt.Columns.Add("血氧浓度");
        dt.Columns.Add("体温");
        dt.Columns.Add("数据采集时间");

        foreach (var item in healthData)
        {
            DataRow row = dt.NewRow();
            row["数据ID"] = item.数据ID;
            row["老人ID"] = item.老人ID;
            row["心率"] = item.心率;
            row["收缩压"] = item.收缩压;
            row["舒张压"] = item.舒张压;
            row["血氧浓度"] = item.血氧浓度;
            row["体温"] = item.体温;
            row["数据采集时间"] = item.数据采集时间;
            dt.Rows.Add(row);
        }

        // 设置 Excel 输出
        Response.Clear();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment;filename=HealthData.xlsx");
        Response.Charset = "";
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

        using (ExcelPackage pck = new ExcelPackage())
        {
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add("HealthData");

            // 加载 DataTable 数据
            ws.Cells["A1"].LoadFromDataTable(dt, true);
            ws.Cells[ws.Dimension.Address].AutoFitColumns();

            var stream = new MemoryStream(pck.GetAsByteArray());
            stream.WriteTo(Response.OutputStream);
            Response.Flush();
            Response.End();
        }
    }




    private List<dynamic> GetFilteredHealthData(DateTime? startDate, DateTime? endDate)
    {
        using (var db = new DataClasses1DataContext())
        {
            int userId = Convert.ToInt32(Session["CustomerId"]);
            var boundElderlyIds = db.RelativeOldMapping
                             .Where(r => r.子女id == userId && r.审核状态 == true)
                             .Select(r => r.老人id.ToString())
                             .ToList();

            var query = db.Theath健康数据.Where(h => boundElderlyIds.Contains(h.old_id));

            if (startDate.HasValue)
            {
                query = query.Where(h => h.数据采集时间 >= startDate.Value);
                System.Diagnostics.Debug.WriteLine($"筛选开始日期: {startDate.Value}");
            }

            if (endDate.HasValue)
            {
                query = query.Where(h => h.数据采集时间 <= endDate.Value);
                System.Diagnostics.Debug.WriteLine($"筛选结束日期: {endDate.Value}");
            }

            var result = query.Select(h => new
            {
                数据ID = h.dataid,
                老人ID = h.old_id,
                心率 = h.心率,
                收缩压 = h.收缩压,
                舒张压 = h.舒张压,
                血氧浓度 = h.血氧浓度,
                体温 = h.体温,
                数据采集时间 = h.数据采集时间
            }).ToList<dynamic>();

            System.Diagnostics.Debug.WriteLine($"查询结果数量: {result.Count}");
            return result;
        }
    }


    protected void btnExportPDF_Click(object sender, EventArgs e)
    {
        DateTime? startDate = string.IsNullOrEmpty(txtStartDate.Text) ? (DateTime?)null : DateTime.Parse(txtStartDate.Text);
        DateTime? endDate = string.IsNullOrEmpty(txtEndDate.Text) ? (DateTime?)null : DateTime.Parse(txtEndDate.Text);

        var healthData = GetFilteredHealthData(startDate, endDate);

        // 设置 PDF 输出
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=HealthData.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        using (var document = new Document())
        {
            PdfWriter.GetInstance(document, Response.OutputStream);
            document.Open();

            // 添加标题
            var titleFont = FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 16);
            document.Add(new Paragraph("健康数据报告", titleFont) { Alignment = Element.ALIGN_CENTER });

            // 添加空白行
            document.Add(new Paragraph("\n"));

            // 添加图表图片
            string chartImagePath = Server.MapPath("~/chart.png");
            if (File.Exists(chartImagePath))
            {
                var chartImage = iTextSharp.text.Image.GetInstance(chartImagePath);
                chartImage.ScaleToFit(500f, 300f); // 调整图像大小
                chartImage.Alignment = Element.ALIGN_CENTER;
                document.Add(chartImage);

                // 添加空白行
                document.Add(new Paragraph("\n"));
            }

            // 创建表格
            PdfPTable table = new PdfPTable(8) { WidthPercentage = 100 }; // 8 列
            table.AddCell("数据ID");
            table.AddCell("老人ID");
            table.AddCell("心率");
            table.AddCell("收缩压");
            table.AddCell("舒张压");
            table.AddCell("血氧浓度");
            table.AddCell("体温");
            table.AddCell("数据采集时间");

            // 填充数据
            foreach (var item in healthData)
            {
                table.AddCell(item.数据ID.ToString());
                table.AddCell(item.老人ID.ToString());
                table.AddCell(item.心率.ToString());
                table.AddCell(item.收缩压.ToString());
                table.AddCell(item.舒张压.ToString());
                table.AddCell(item.血氧浓度.ToString());
                table.AddCell(item.体温.ToString());
                table.AddCell(item.数据采集时间.ToString());
            }

            document.Add(table);
            document.Close();
        }
        Response.End();
    }
    public class SaveChartImageHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            if (context.Request.Files.Count > 0)
            {
                var file = context.Request.Files[0];
                string filePath = context.Server.MapPath("~/chart.png");
                file.SaveAs(filePath);
                context.Response.Write("图表已保存");
            }
            else
            {
                context.Response.StatusCode = 400;
                context.Response.Write("没有上传文件");
            }
        }

        public bool IsReusable => false;
    }


    protected void typebtn_Click(object sender, EventArgs e)
    {
        if (Panel1.Visible)
        {
            Panel1.Visible = false;
            typetxt.Text = "";
        }
        else
        {
            Panel1.Visible = true;

            string filePath = @"D:\web系统与技术\Elderlyhealth\Elderlyhealths\Healthhtxt\增强身体健康方法.txt";

            using (StreamReader reader = new StreamReader(filePath))
            {
                string line;
                typetxt.Text = "";
                while ((line = reader.ReadLine()) != null)
                {
                    typetxt.Text += line + "\n";
                }
            }
        }
    }
}